Component({
  methods: {
    // 对外暴露：打开媒体查看（图片预览或PDF打开）
    open(inputFiles: Array<string | { url?: string; name?: string; fileUrl?: string; file_url?: string; path?: string; file?: string; downloadUrl?: string }>) {
      if (!inputFiles || inputFiles.length === 0) {
        wx.showToast({ title: '暂无可查看文件', icon: 'none' });
        return;
      }

      type FileInfo = { url: string; name?: string };
      const safeTrim = (s?: string) => {
        if (typeof s !== 'string') return '';
        const t = s.trim();
        try {
          // 尝试解码以便识别扩展名
          return decodeURIComponent(t);
        } catch (_) {
          return t;
        }
      };
      const pickUrl = (obj: any) => safeTrim(obj?.url)
        || safeTrim(obj?.fileUrl)
        || safeTrim(obj?.file_url)
        || safeTrim(obj?.downloadUrl)
        || safeTrim(obj?.path)
        || safeTrim(obj?.file);

      // 若收到形如 ["[{\"url\":\"...pdf\"}]"] 的单元素 JSON 字符串，先解析
      let normalizedInputs: any = inputFiles;
      try {
        if (Array.isArray(inputFiles) && inputFiles.length === 1 && typeof inputFiles[0] === 'string') {
          const str = (inputFiles[0] as string).trim();
          // 去掉外层多余引号的情况
          const unquoted = /^"\[/.test(str) || /^'\[/.test(str) ? str.slice(1, -1) : str;
          if (/^\[/.test(unquoted) || /^\{/.test(unquoted)) {
            const parsed = JSON.parse(unquoted);
            if (Array.isArray(parsed)) {
              normalizedInputs = parsed;
            } else if (parsed && typeof parsed === 'object') {
              normalizedInputs = [parsed];
            }
          }
        }
      } catch (e) {
        console.warn('media-viewer JSON parse skipped', e);
      }
      const toFileInfo = (item: any): FileInfo | null => {
        if (!item) return null;
        if (typeof item === 'string') return { url: safeTrim(item) };
        if (typeof item === 'object') {
          const url = pickUrl(item);
          if (url) return { url, name: item.name };
        }
        return null;
      };

      const files: FileInfo[] = (normalizedInputs as any[]).map(toFileInfo).filter((x: any) => !!x) as FileInfo[];
      if (files.length === 0) {
        wx.showToast({ title: '暂无可查看文件', icon: 'none' });
        return;
      }
      console.log('files', files);

      const normalizeUrlForExt = (url: string) => {
        try {
          const decoded = (() => { try { return decodeURIComponent(url); } catch { return url; } })();
          const noHash = decoded.split('#')[0];
          const noQuery = noHash.split('?')[0];
          return noQuery.toLowerCase();
        } catch (_) {
          return (url || '').toLowerCase();
        }
      };
      const hasExt = (url: string, ext: string) => normalizeUrlForExt(url).endsWith(ext);
      const isImage = (url: string) => ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp'].some(e => hasExt(url, e));
      const isPdf = (url: string) => hasExt(url, '.pdf');

      const imageFiles: FileInfo[] = files.filter(f => isImage(f.url));
      const pdfFiles: FileInfo[] = files.filter(f => isPdf(f.url));

      const openImages = () => {
        if (imageFiles.length === 0) {
          wx.showToast({ title: '暂无可预览图片', icon: 'none' });
          return;
        }
        wx.previewImage({
          urls: imageFiles.map(f => f.url),
          current: imageFiles[0].url
        });
      };

      const openPdf = (url: string) => {
        if (!url) return;
        wx.showLoading({ title: '打开中...' });
        wx.downloadFile({
          url,
          success: (res) => {
            try {
              const statusCode: any = (res as any).statusCode;
              const headers: any = (res as any).header || (res as any).headers;
              console.log('media-viewer downloadFile success', { statusCode, headers, tempFilePath: res.tempFilePath });
              if (statusCode && statusCode !== 200) {
                wx.hideLoading();
                wx.showToast({ title: `下载失败(${statusCode})`, icon: 'none' });
                return;
              }
              const contentType = headers ? (headers['Content-Type'] || headers['content-type'] || '') : '';
              const fileType = /pdf/i.test(contentType) ? 'pdf' : 'pdf';
              wx.openDocument({
                filePath: res.tempFilePath,
                fileType, // 强制声明为 pdf，更兼容某些不带扩展名的临时路径
                showMenu: true,
                success: () => {
                  console.log('media-viewer openDocument success');
                },
                fail: (e) => {
                  console.warn('media-viewer openDocument fail', e);
                  wx.showToast({ title: '无法打开PDF', icon: 'none' });
                },
                complete: () => wx.hideLoading()
              });
            } catch (e) {
              wx.hideLoading();
              console.warn('media-viewer openPdf error', e);
              wx.showToast({ title: '打开PDF异常', icon: 'none' });
            }
          },
          fail: (e) => {
            wx.hideLoading();
            console.warn('media-viewer downloadFile fail', e);
            wx.showToast({ title: '下载PDF失败', icon: 'none' });
          }
        });
      };

      const getDisplayName = (f: FileInfo) => {
        if (f.name && typeof f.name === 'string') return f.name;
        try {
          const pathname = f.url.split('?')[0].split('#')[0];
          return pathname.substring(pathname.lastIndexOf('/') + 1) || '文件';
        } catch (_) {
          return '文件';
        }
      };

      if (imageFiles.length > 0 && pdfFiles.length > 0) {
        wx.showActionSheet({
          itemList: ['查看图片', '查看PDF'],
          success: (res) => {
            if (res.tapIndex === 0) {
              openImages();
            } else if (res.tapIndex === 1) {
              if (pdfFiles.length === 1) {
                openPdf(pdfFiles[0].url);
              } else {
                const names = pdfFiles.map(getDisplayName);
                wx.showActionSheet({
                  itemList: names,
                  success: (r) => openPdf(pdfFiles[r.tapIndex].url)
                });
              }
            }
          }
        });
        return;
      }

      if (imageFiles.length > 0) {
        openImages();
        return;
      }

      if (pdfFiles.length > 0) {
        if (pdfFiles.length === 1) {
          openPdf(pdfFiles[0].url);
        } else {
          const names = pdfFiles.map(getDisplayName);
          wx.showActionSheet({
            itemList: names,
            success: (r) => openPdf(pdfFiles[r.tapIndex].url)
          });
        }
        return;
      }

      // 兜底：若根据 url 判断失败，但根据名称能判断 PDF，则尝试打开
      const pdfByName = files.find(f => /\.pdf$/i.test((f.name || '').toLowerCase()));
      if (pdfByName) {
        openPdf(pdfByName.url);
        return;
      }

      wx.showToast({ title: '不支持的文件类型', icon: 'none' });
    }
  }
});


